package com.lzp.spider.controller;

import com.lzp.spider.arg.PageArg;
import com.lzp.spider.dao.JobDetailRepository;
import com.lzp.spider.pojo.JobDetail;
import com.lzp.spider.service.SpiderService;
import com.lzp.spider.vo.JobDetailVO;
import com.lzp.spider.vo.PageVO;
import com.lzp.spider.vo.ResultVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import us.codecraft.webmagic.Spider;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;

import java.util.ArrayList;
import java.util.List;

@RestController
public class SpiderController {
    @Autowired
    SpiderService spiderService;
    @Autowired
    private JobDetailRepository jobDetailRepository;

    @ApiOperation("此接口用于运行爬虫程序")
    @RequestMapping(value = "/spider",method = RequestMethod.POST)
    public ResultVO spider(){
        Spider.create(spiderService).addUrl(spiderService.getURL()).run();
        ResultVO resultVO = new ResultVO();
        resultVO.setCode(0);
        resultVO.setMsg("success");
        return resultVO;
    }

    @ApiOperation("列出爬取到的职位信息")
    @RequestMapping(value = "/job_list",method = RequestMethod.POST)
    public ResultVO<PageVO<JobDetailVO>> getJobList(@RequestBody PageArg arg){
        arg.validate();
        Pageable pageable = PageRequest.of(arg.getPageNo() - 1, arg.getPageSize());

        //封装数据
        Page<JobDetail> jobDetailPage = jobDetailRepository.findAll(pageable);
        List<JobDetail> jobDetailList = jobDetailPage.getContent();
        List<JobDetailVO> list = new ArrayList<>();
        for (JobDetail jobDetail : jobDetailList) {
            JobDetailVO jobDetailVO = new JobDetailVO();
            BeanUtils.copyProperties(jobDetail,jobDetailVO);
            list.add(jobDetailVO);
        }
        PageVO<JobDetailVO> res = PageVO.<JobDetailVO>builder()
                .total(jobDetailPage.getTotalPages())
                .pageSize(arg.getPageSize())
                .currentPage(arg.getPageNo())
                .list(list)
                .build();

        ResultVO<PageVO<JobDetailVO>> resultVO = new ResultVO<>();
        resultVO.setCode(0);
        resultVO.setMsg("success");
        resultVO.setData(res);
        return resultVO;
    }
}
